var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

function Point(x, y){
    this.x = x;
    this.y = y;
}

function Ball(x, y, angle, speed, radius){
    this.speed = speed;
    this.radius = radius;
    this.p = new Point(x, y);
    this.angle = angle;
}

function draw(){
    context.fillStyle = '#cccccc';
    context.fillRect(0, 0, 500, 500);

    context.strokeRect(0, 0, 500, 500);

    for (var i = 0, len = balls.length; i < len; i++) {
        // uploadBall(balls[i]);
        context.beginPath();
        context.fillStyle = 'green';
        context.arc(balls[i].x, balls[i].y, balls[i].radius, 0, 2 * Math.PI);
        context.fill();
        context.closePath();
    }
    testWalls();
    updateBall();
    collide();
}


function canStartHere(ball) {
    var retval = true;
    for(var i = 0; i < balls.length; i++) {
        if (hitTestCircle(ball, balls[i]))
        retval &= false;
    }
    return retval;
}

function hitTestCircle(ball1, ball2) {
    var retval = false;
    var dx = ball1.x - ball2.x;
    var dy = ball1.y - ball2.y;

    var distance = (dx * dx + dy * dy);
    if (distance <= (ball1.radius + ball2.radius) * (ball1.radius + ball2.radius)) {
        retval = true;
    }
    return retval;
}

/**
 * 更新球的轨迹
 */
function updateBall(){
    for (var i = 0, len = balls.length; i < len; i++) {
        balls[i].x += balls[i].velocityx;
        balls[i].y += balls[i].velocityy;
    }
}

/**
 * 检测是否和墙碰撞了。如果碰撞了，就向对角方向。
 */
function testWalls(){
    for (var i = 0, len = balls.length; i < len; i++) {
        if (balls[i].x - balls[i].radius < 0 || balls[i].x + balls[i].radius > canvas.width) {
            balls[i].velocityx *= -1;
        } else if (balls[i].y - balls[i].radius < 0 || balls[i].y + balls[i].radius > canvas.height) {
            balls[i].velocityy *= -1;
        }
    }
}

function collide(){
    for(var i = 0, len = balls.length; i < len; i++){
        for(var j = i + 1; j < len; j ++) {
            if (hitTestCircle(balls[i], balls[j])) {
                collideBalls(balls[i], balls[j]);
            }
        }
    }
}
//
// function collideBalls(ball1, ball2){
//     var dx = ball1.x - ball2.x;
//     var dy = ball1.y - ball2.y;
//     var collisionAngle = Math.atan2(dy, dx);
//     var speed1 = Math.sqrt(ball1.velocityx * ball1.velocityx + ball1.velocityy * ball1.velocityy);
//     var speed2 = Math.sqrt(ball2.velocityx * ball2.velocityx + ball2.velocityy * ball2.velocityy);
//     var direction1 = Math.atan2(ball1.velocityy, ball1.velocityx);
//     var direction2 = Math.atan2(ball2.velocityy, ball2.velocityx);
//     var velocityx_1 = speed1 * Math.cos(direction1 - collisionAngle);
//     var velocityy_1 = speed1 * Math.cos(direction1 - collisionAngle);
//     var velocityx_2 = speed2 * Math.cos(direction2 - collisionAngle);
//     var velocityy_2 = speed2 * Math.cos(direction2 - collisionAngle);
//     var fina1_velocityx_1 = ((ball1.mass - ball2.mass) * velocityx_1 + (ball2.mass + ball2.mass) * velocityx_2) / (ball1.mass + ball2.mass);
// }


function collideBalls(ball1,ball2) {

    var dx = ball1.x - ball2.x;
    var dy = ball1.y - ball2.y;
    console.log('dx', dx);
    console.log('dy', dy);

    var collisionAngle = Math.atan2(dy, dx);

    var speed1 = Math.sqrt(ball1.velocityx * ball1.velocityx + ball1.velocityy * ball1.velocityy);
    var speed2 = Math.sqrt(ball2.velocityx * ball2.velocityx + ball2.velocityy * ball2.velocityy);

    var direction1 = Math.atan2(ball1.velocityy, ball1.velocityx);
    var direction2 = Math.atan2(ball2.velocityy, ball2.velocityx);

    var velocityx_1 = speed1 * Math.cos(direction1 - collisionAngle);
    var velocityy_1 = speed1 * Math.sin(direction1 - collisionAngle);
    var velocityx_2 = speed2 * Math.cos(direction2 - collisionAngle);
    var velocityy_2 = speed2 * Math.sin(direction2 - collisionAngle);

    var final_velocityx_1 = ((ball1.mass - ball2.mass) * velocityx_1 + (ball2.mass + ball2.mass) * velocityx_2)/(ball1.mass + ball2.mass);
    var final_velocityx_2 = ((ball1.mass + ball1.mass) * velocityx_1 + (ball2.mass - ball1.mass) * velocityx_2)/(ball1.mass + ball2.mass);

    var final_velocityy_1 = velocityy_1;
    var final_velocityy_2 = velocityy_2;

    ball1.velocityx = Math.cos(collisionAngle) * final_velocityx_1 + Math.cos(collisionAngle + Math.PI/2) * final_velocityy_1;
    ball1.velocityy = Math.sin(collisionAngle) * final_velocityx_1 + Math.sin(collisionAngle + Math.PI/2) * final_velocityy_1;
    ball2.velocityx = Math.cos(collisionAngle) * final_velocityx_2 + Math.cos(collisionAngle + Math.PI/2) * final_velocityy_2;
    ball2.velocityy = Math.sin(collisionAngle) * final_velocityx_2 + Math.sin(collisionAngle + Math.PI/2) * final_velocityy_2;

    ball1.x += ball1.velocityx;
    ball1.y += ball1.velocityy;
    ball2.x += ball2.velocityx;
    ball2.y += ball2.velocityy;
}


function draw(){
    context.fillStyle = '#cccccc';
    context.fillRect(0, 0, 500, 500);

    context.strokeRect(0, 0, 500, 500);

    for (var i = 0, len = balls.length; i < len; i++) {
        // uploadBall(balls[i]);
        context.beginPath();
        context.fillStyle = 'green';
        context.arc(balls[i].x, balls[i].y, balls[i].radius, 0, 2 * Math.PI);
        context.stroke();
        context.closePath();

        // 矢量方向
        context.beginPath();
        context.moveTo(balls[i].x, balls[i].y);
        context.lineTo(balls[i].x + balls[i].velocityx * 5, balls[i].y + balls[i].velocityy * 5);
        context.stroke();
        context.beginPath();
        context.arc(balls[i].x + balls[i].velocityx * 5, balls[i].y + balls[i].velocityy * 5, 2, 0, 2* Math.PI);
        context.stroke();

        context.closePath();
    }
    console.log(balls);
    collideBalls(balls[0], balls[1])
    // testWalls();
    // updateBall();
    // collide();
}


var balls = null;

(function(){

    balls = [];
    // balls[0] = new Ball(100, 100, 30, 3, 10)

    // for (var x = 0; x < 2; x++) {
    //     var tempRadius = 20;
    //     var placeOk = false;
    //     var tempBall = null;
    //     var i = 0;
    //     while (!placeOk) {
    //         var tempX = (Math.floor(Math.random() * (canvas.width - 2 *tempRadius)) + tempRadius);
    //         var tempY = (Math.floor(Math.random() * (canvas.height - 2 * tempRadius)) + tempRadius);
    //
    //         var tempSpeed = 4;
    //         var tempAngle = Math.floor(Math.random() * 360);
    //         var tempRadians = tempAngle * Math.PI / 180;
    //         var tempvelocityx = Math.cos(tempRadians) * tempSpeed;
    //         var tempvelocityy = Math.sin(tempRadians) * tempSpeed;
    //         tempBall = {
    //             x: tempX,
    //             y: tempY,
    //             radius: tempRadius,
    //             speed: tempSpeed,
    //             angle: tempAngle,
    //             velocityx: tempvelocityx,
    //             velocityy: tempvelocityy,
    //             mass: tempRadius
    //         };
    //         placeOk = canStartHere(tempBall);
    //         if (!placeOk) {
    //             console.log('pass ball:', tempBall);
    //         }
    //     }
    //     console.log('ok ball:', tempBall);
    //     balls.push(tempBall);
    // }

    balls[0] = {
        x: 100,
        y: 100,
        radius: 50,
        angle: 90,
        speed: 10,
        velocityx: 0,
        velocityy: 0,
        mass: 50
    };

    var tempRadians = balls[0].angle * Math.PI / 180;
    var tempvelocityx = Math.cos(tempRadians) * balls[0].speed;
    var tempvelocityy = Math.sin(tempRadians) * balls[0].speed;
    balls[0].velocityx = tempvelocityx;
    balls[0].velocityy = tempvelocityy;

    balls[1] = {
        x: 180,
        y: 160,
        radius: 50,
        speed: 10,
        angle: 180,
        velocityx: 4,
        velocityy: 4,
        mass: 50
    };

    tempRadians = balls[1].angle * Math.PI / 180;
    tempvelocityx = Math.cos(tempRadians) * balls[1].speed;
    tempvelocityy = Math.sin(tempRadians) * balls[1].speed;
    balls[1].velocityx = tempvelocityx;
    balls[1].velocityy = tempvelocityy;

    draw();
})();